<?php

class Mod_Reset_Password extends CI_Model {
	
	private $table = 'tbl_token';
	private $field = array(
						'email' => 'email',
						'token'	=> 'token',
						'created' => 'created_at'
					);
    
	function isEmailExists($email){
		$this->db->select(field('id'))
				->where(field('email'), $email)
				->get(table('user'));
				
		if($this->db->affected_rows() == 1){
			return TRUE;	
		}
		
		return FALSE;
	}
	
	function addTempReset($email, $token){
		$data = array(
					   $this->field['email'] => $email,
					   $this->field['token']  => $token
					);
		
		$this->db->insert($this->table, $data); 
		return $this->db->affected_rows();
	}
	
	public function getEmailReset($token){
		$this->db->select($this->field['email'])
				->where($this->field['token'], $token);
				
		$result = $this->db->get($this->table);
		if($result->num_rows() > 0){
			$row = $result->row_array();
			return $row[$this->field['email']];	
		}
		
		return FALSE;
	}
		
	public function resetPassword($password, $email, $token){
		// Remove token
		$this->db->delete($this->table, $this->field['token'].' = "'.$token.'"');
		// Update user's password
		$this->db->where(field('email'), $email)
				->set(field('password'), mkpwd($password))
				->set(field('updatedAt'), 'NOW()', FALSE);
		$this->db->update(table('user'));
		return $this->db->affected_rows();
	}
		
	public function isExistToken($token){
		$this->db->select($this->field['token'])
				->where($this->field['token'], $token)
				->get($this->table);   
				
		return $this->db->affected_rows();
	}
}
